package com.zxmr.rabbit;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ChannelFactory {

	static Connection connection = null;
	static ConnectionFactory factory = null;
	static{
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername("admin");
		factory.setPassword("admin");
		factory.setHost("127.0.0.1");
		factory.setPort(5672);
		factory.setVirtualHost("/");
		try
		{
			connection = factory.newConnection();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	    
	}
	
	public static Channel createChannel()
	{
		if(connection != null && connection.isOpen())
			try {
				return connection.createChannel();
			} catch (IOException e) {
				e.printStackTrace();
				return null;
		}
		else
		{
			ConnectionManager.resetConnection();
		}
		return null;
	}
	public static void close()
	{
		try {
			if(connection != null)
			connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection()
	{
		return connection;
	}
	public static boolean reEstablishConnection()
	{
		try
		{
			close();
			connection = factory.newConnection();
			if(connection != null && connection.isOpen())
				return true;
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return false;
	}
}
